package mastermind.database;

import java.io.*;

/**
 * Backing store to store user data.
 * @author Brendan
 *
 */
public class TextDatabase {
	GameUserTable table;
	final static String filename = "database.db";
	
	public TextDatabase() {
		table = null;
	}
	
	/**
	 * synchronized login
	 * @param userName the username to use
	 * @param password the password maching the username
	 * @returns true on valid credentials 
	 */
	public synchronized boolean validCredentials(String userName,String password) {
		rehash();
		return table.checkLogin(userName, password);
	}
	
	/**
	 * synchronized validation of checking if user exists
	 * @param userName username to check
	 */
	public synchronized boolean userExists(String userName) {
		rehash();
		GameUserEntry temp;
		temp = table.getUser(userName);
		if(temp == null)
		{
			return false;
		}
		return true;
		//return table.getUser(userName) == null ? false : true;
	}
	
	/**
	 * synchronized registering
	 * @param firstName Users firstname
	 * @param lastName Users lastname
	 * @param userName Users login
	 * @param password Users login password
	 * @param phoneNumber Contact number
	 */
	public synchronized void regiser(String firstName, String lastName, String userName, String password, String phoneNumber) {
		GameUserEntry newUser = new GameUserEntry();
		newUser.setAll(firstName, lastName, userName, password, phoneNumber);
		table.addUser(newUser);
		flush();
	}
	
	/**
	 * Flush all data to disk
	 */
	private synchronized void flush() {
		FileOutputStream fos = null;
		ObjectOutputStream os = null;
		
		try {
			fos = new FileOutputStream(filename);
			os = new ObjectOutputStream(fos);
			os.writeObject(table);
			os.close();
		} catch(IOException ex)
		{
			ex.printStackTrace();
		}
	}
	
	/**
	 * Read all data from disk
	 */
	private synchronized void rehash() {
		FileInputStream fis = null;
		ObjectInputStream in = null;
		
		try {
			fis = new FileInputStream(filename);
			in = new ObjectInputStream(fis);
			table = (GameUserTable)in.readObject();
			in.close();
		} catch(ClassNotFoundException ex)
		{
			ex.printStackTrace();
		} catch(FileNotFoundException ex) {
			table = new GameUserTable();
			flush();
		} catch(IOException ex) { 
			ex.printStackTrace();
		}
	}
}